package com.qyhl.webtv.module_news.news.picturenews;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.ninegrid.preview.HackyViewPager;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.PictureBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.ZoomOutPageTransformer;
import com.qyhl.webtv.module_news.utils.view.bottomview.TestBottomLayout;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;
import uk.co.senab.photoview.PhotoView;

/**
 * Created by qyhl on 2017/11/29.
 * 图片新闻
 */

@Route(path = ARouterPathConstant.PICTURE_NEWS_ACTIVITY)
public class PictureNewsActivity extends BaseActivity implements PictureNewsContract.PictureNewsView, BaseActivity.InputListener {
    @BindView(R2.id.viewPager)
    HackyViewPager viewPager;
    @BindView(R2.id.bottom_layout)
    TestBottomLayout bottomLayout;
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.text_text)
    LinearLayout mNesToolBar;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.activity_main)
    LinearLayout activityMain;

    private PictureNewsPresenter mPresenter;
    private boolean editbarEnable = true;

    String newsId;

    String sectionId;

    private PictureBean mBean;

    private boolean isCollect;

    //是否全屏
    boolean isFulllScreen = false;

    private RequestOptions options;

    private SamplePagerAdapter mAdapter;

    private LoadingDialog.Builder builder;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置黑色主题
        setTheme(R.style.PhotoBackTheme);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_news_picture;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PictureNewsPresenter(this);
        newsId = getIntent().getStringExtra("id");
        sectionId = getIntent().getStringExtra("section");
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.count(newsId);
        mPresenter.getDetail(newsId);
    }

    /**
     * 初始化
     */
    private void initView() {
        addInputListener(this);
        bottomLayout.setTtitle("");
        bottomLayout.setData("");
        bottomLayout.setSource("");
        bottomLayout.setScan("");


        editbar.isHasEdit(false).setShareIconRes(R.drawable.share_more_icon);

        options = new RequestOptions()
                .placeholder(R.drawable.cover_normal_default)
                .error(R.drawable.cover_error_large_default)
                .priority(Priority.HIGH);

        builder = new LoadingDialog.Builder(PictureNewsActivity.this);
        builder.setTitle("请稍等...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        loadMask.setStatus(LoadingLayout.Loading);
        //重新加载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(newsId);
        });

        //底部输入框监听
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {

            }

            @Override
            public void onShare() {
                MPermissionUtils.requestPermissionsResult(PictureNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        MShareBoard shareBoard = new MShareBoard(PictureNewsActivity.this, newsId, mBean.getTitle(), mBean.getContent().get(0).getFilepath() == null ? "" : mBean.getContent().get(0).getFilepath(), mBean.getSummary(), 2, true);
                        shareBoard.showPopupWindow();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(PictureNewsActivity.this);

                    }
                });
            }

            @Override
            public void onCollect(final boolean isCollect) {
                if (editbarEnable) {
                    editbarEnable = false;
                    builder.show();

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                if (isCollect) {
                                    mPresenter.collect(newsId);
                                } else {
                                    mPresenter.cancelCollect(newsId);
                                }
                            } else {
                                builder.dismiss();
                                RouterManager.routerLogin(PictureNewsActivity.this, 0);
                                editbarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            editbarEnable = true;
                        }
                    });
                }

            }

            @Override
            public void onComment() {

                Bundle bundle = new Bundle();
                bundle.putString("title", mBean.getTitle());
                bundle.putString("sectionId", sectionId);
                bundle.putString("id", newsId);
                RouterManager.router(ARouterPathConstant.NEWS_COMMENT, bundle);
            }
        });

        builder.getmDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
//                OkHttpUtils.getInstance().cancelTag(PictureNewsActivity.this);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 设置详情
     *
     * @param bean
     */
    @Override
    public void setDetail(PictureBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        mBean = bean;
        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), mBean.getReferName(), "0");
        }
        //是否收藏
        isCollect = StringUtils.isNotEmpty(mBean.getIscollect()) && "1".equals(mBean.getIscollect());

        editbar.setCollect(isCollect);

        mAdapter = new SamplePagerAdapter(mBean);

        viewPager.setAdapter(mAdapter);

        bottomLayout.setTtitle(mBean.getTitle());

        bottomLayout.setAuthor(mBean.getWriter());

        bottomLayout.setData(DateUtils.detailDateTranslate(mBean.getPublishDate()));

        bottomLayout.setSource(mBean.getReferName());
        try {
            int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
            if (minPlay == 0) {
                bottomLayout.setScan("");
            } else {
                //判断评论数是否大于最少评论数
                if (StringUtils.isEmpty(mBean.getHitCount())) {
                    bottomLayout.setScan("");
                } else if (Integer.parseInt(mBean.getHitCount()) >=
                        minPlay) {
                    bottomLayout.setScan(StringUtils.transformNum(mBean.getHitCount() + ""));
                } else {
                    bottomLayout.setScan("");
                }
            }

        } catch (Exception e) {
            Log.i("error_scan", e.getMessage());
        }

        bottomLayout.setPage("1/" + mBean.getContent().size());
        if (mBean.getContent() != null && mBean.getContent().size() > 0) {
            bottomLayout.setContent(mBean.getContent().get(0).getInfo());
        }

        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                bottomLayout.setTtitle(mBean.getTitle());

                bottomLayout.setContent(mBean.getContent().get(position).getInfo());

                bottomLayout.setPage((position + 1) + "/" + mBean.getContent().size());

                bottomLayout.setData(DateUtils.mTranslateDate(mBean.getPublishDate()));

                bottomLayout.setSource(mBean.getReferName());

                bottomLayout.setAuthor(mBean.getWriter());
                try {
                    int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
                    if (minPlay == 0) {
                        bottomLayout.setScan("");
                    } else {
                        //判断评论数是否大于最少评论数
                        if (StringUtils.isEmpty(mBean.getHitCount())) {
                            bottomLayout.setScan("");
                        } else if (Integer.parseInt(mBean.getHitCount()) >=
                                minPlay) {
                            bottomLayout.setScan(StringUtils.transformNum(mBean.getHitCount() + ""));
                        } else {
                            bottomLayout.setScan("");
                        }
                    }

                } catch (Exception e) {
                    Log.i("error_scan", e.getMessage());
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 收藏成功
     *
     * @param msg
     */
    @Override
    public void collectSuccess(String msg) {
        builder.dismiss();
        Toasty.normal(PictureNewsActivity.this, msg, Toast.LENGTH_SHORT).show();
        editbar.setCollect(true);
        editbarEnable = true;

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoCollect(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), "3");
        }
    }

    /**
     * 收藏失败
     *
     * @param msg
     */
    @Override
    public void collectError(String msg) {
        builder.dismiss();
        Toasty.normal(PictureNewsActivity.this, msg, Toast.LENGTH_SHORT).show();
        editbarEnable = true;
    }

    /**
     * 取消收藏成功
     */
    @Override
    public void cancelCollectSuccess() {
        builder.dismiss();
        editbar.setCollect(false);
        BusFactory.getBus().post(new Event.CollectMessage(false));
        editbarEnable = true;
    }

    /**
     * 取消收藏失败
     *
     * @param msg
     */
    @Override
    public void cancelCollectError(String msg) {
        builder.dismiss();
        Toasty.normal(PictureNewsActivity.this, msg, Toast.LENGTH_SHORT).show();
        editbarEnable = true;
    }

    @Override
    public void cancelCollect() {
        builder.dismiss();
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        editbar.changeStateDefault(this);
    }

    class SamplePagerAdapter extends PagerAdapter {

        private final PictureBean mPhotoNews;

        public SamplePagerAdapter(PictureBean news) {
            this.mPhotoNews = news;
        }

        @Override
        public int getCount() {
            return mPhotoNews.getContent().size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());

            Glide.with(PictureNewsActivity.this)
                    .load(mPhotoNews.getContent().get(position).getFilepath())
                    .apply(options)
                    .into(photoView);

            photoView.setOnPhotoTapListener((view, v, v1) -> {
                if (!isFulllScreen) {
                    //全屏
                    WindowManager.LayoutParams params = getWindow().getAttributes();
                    params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    getWindow().setAttributes(params);
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                    bottomLayout.setVisibility(View.INVISIBLE);
                    mNesToolBar.setVisibility(View.INVISIBLE);

                } else {
                    //取消全屏
                    WindowManager.LayoutParams params = getWindow().getAttributes();
                    params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    getWindow().setAttributes(params);
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                    bottomLayout.setVisibility(View.VISIBLE);
                    mNesToolBar.setVisibility(View.VISIBLE);
                }
                isFulllScreen = !isFulllScreen;
            });
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("图片新闻详情");
        MobclickAgent.onResume(this);

        ActionLogUtils.getInstance().onResume(this, ActionConstant.NEWSDETAIL);

    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("图片新闻详情");
        MobclickAgent.onPause(this);
        ActionLogUtils.getInstance().onPause(this, ActionConstant.NEWSDETAIL);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), mBean.getReferName(), "1");
        }
    }
}
